package com.xyht.sca_s.student_manage_system.modules.org.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.sca_s.student_manage_system.auth.entity.Node;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.org.entity.OrgNode;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgUserRelation;
import com.xyht.sca_s.student_manage_system.modules.org.entity.req.*;
import com.xyht.sca_s.student_manage_system.modules.org.entity.resp.*;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.org.service.SmsOrgStructureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.org.service.SmsOrgUserRelationService;
import com.xyht.sca_s.student_manage_system.modules.org.util.CommonUtil;
import com.xyht.sca_s.student_manage_system.modules.org.util.NodeTreeUtil;
import com.xyht.sca_s.student_manage_system.modules.org.util.NodeUtil;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsTeacherInfo;
import com.xyht.sca_s.student_manage_system.modules.teacher.entity.SmsUserTeacherRelation;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsTeacherInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.teacher.mapper.SmsUserTeacherRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsSearchUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_ERR;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskTypeConstant.TASK_TYPE_TEACHER;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.OrgObjectTypeConstant.ORG_OBJECT_TYPE_ROLE;
import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.*;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.REASON_FAIL;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskNameExample.TASK_NAME_ORG_TEACHER_IMPORT;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_DONE;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.OrgTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.org.constants.UpdateTypeConstant.UPDATE_TYPE_UPDATE_ADD;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.TeacherAndStudentFlag.TEACHER_FLAG;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.commonConstant.DEFAULT_PASSWORD;
import static com.xyht.sca_s.student_manage_system.modules.user.constant.DefaultRole.ROLE_TEACHER;

import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织架构 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-11-27
 */
@Service
public class SmsOrgStructureServiceImpl extends ServiceImpl<SmsOrgStructureMapper, SmsOrgStructure> implements SmsOrgStructureService {
    @Resource
    private SmsOrgStructureMapper smsOrgStructureMapper;

    @Resource
    private SmsImportTaskMapper smsImportTaskMapper;
    @Resource
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private SmsTeacherInfoMapper smsTeacherInfoMapper;
    @Resource
    private SmsUserTeacherRelationMapper smsUserTeacherRelationMapper;
    @Resource
    private SmsOrgUserRelationMapper smsOrgUserRelationMapper;
    @Resource
    private SmsOrgUserRelationService smsOrgUserRelationService;
    @Resource
    private SmsUserMapper smsUserMapper;
    @Resource
    private SmsRoleMapper smsRoleMapper;
    @Resource
    private SmsUserRoleRelationMapper smsUserRoleRelationMapper;
    @Resource
    private CacheUtil cacheUtil;
    @Resource
    private NodeTreeUtil nodeTreeUtil;
    @Resource
    private CommonUtil commonUtil;

    @Override
    @Async
    public Future<ResponseResult> batchAddUserInfo(Map<String, Object> map, String user_id) {
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
        Integer flag = jsonObject.getInteger("flag");
        Integer type = jsonObject.getInteger("type");//添加类型  1：更新添加  2：覆盖添加
        if (isNullOrEmpty(flag) || isNullOrEmpty(type)) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        SmsImportTask smsImportTask;
        if (flag == TEACHER_FLAG) {
            List<SmsTeacherInfo> teacherInfoList = JSONObject.parseArray(JSON.toJSONString(jsonObject.get("list")), SmsTeacherInfo.class);
            if (teacherInfoList == null || teacherInfoList.size() < 1) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            //创建导入任务
            smsImportTask = new SmsImportTask();
            smsImportTask.setTaskName(TASK_NAME_ORG_TEACHER_IMPORT);
            smsImportTask.setUserId(user_id);
            smsImportTask.setTaskType(TASK_TYPE_TEACHER);
            smsImportTaskMapper.insert(smsImportTask);

            batchAddTeacherInfo(teacherInfoList, smsImportTask.getId(), type);
        }
        return new AsyncResult<>(CommonResult.success());
    }

    @Override
    @Transactional
    public ResponseResult batchDeleteUserInfo(Map<String, Object> map) {
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
        Integer flag = jsonObject.getInteger("flag");
        if (isNullOrEmpty(flag)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<String> list = JSONObject.parseArray(jsonObject.getString("list"), String.class);
        if (list == null || list.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsUser> userList = smsUserMapper.selectBatchIds(list);
        if (userList == null || userList.size() != list.size()) {
            return CommonResult.failed(CommonCodeEnum.USER_ERR_NOT_DELETE);
        }
        //用户表
        smsUserMapper.deleteBatchIds(list);

        //用户组织关系表
        QueryWrapper<SmsOrgUserRelation> orgUserRelationQueryWrapper = new QueryWrapper<>();
        orgUserRelationQueryWrapper.lambda().in(SmsOrgUserRelation::getUserId, list);
        smsOrgUserRelationMapper.delete(orgUserRelationQueryWrapper);

        //用户与用户信息关系表
        //学生或老师信息表
        if (flag == TEACHER_FLAG) {
            QueryWrapper<SmsUserTeacherRelation> userTeacherRelationQueryWrapper = new QueryWrapper<>();
            userTeacherRelationQueryWrapper.lambda().in(SmsUserTeacherRelation::getUserId, list);
            List<SmsUserTeacherRelation> teacherRelationList = smsUserTeacherRelationMapper.selectList(userTeacherRelationQueryWrapper);

            smsUserTeacherRelationMapper.delete(userTeacherRelationQueryWrapper);
            if (teacherRelationList != null && teacherRelationList.size() > 0) {
                List<String> teacherList = new ArrayList<>();
                for (SmsUserTeacherRelation teacherRelation : teacherRelationList) {
                    teacherList.add(teacherRelation.getTchId());
                }
                smsTeacherInfoMapper.deleteBatchIds(teacherList);
            }
        }

        //用户角色关系表
        QueryWrapper<SmsUserRoleRelation> userRoleRelationQueryWrapper = new QueryWrapper<>();
        userRoleRelationQueryWrapper.lambda().in(SmsUserRoleRelation::getUserId, list);
        smsUserRoleRelationMapper.delete(userRoleRelationQueryWrapper);

        return CommonResult.success();
    }


    @Override
    public ResponseResult addUserInfo(Map<String, Object> map) {
        return null;
    }

    @Override
    public ResponseResult deleteUserInfo(Integer id) {


        return null;
    }

    @Resource
    PlatformTransactionManager transactionManager;

    private void batchAddTeacherInfo(List<SmsTeacherInfo> list, String task_id, Integer type) {
        int OFFSET_ROW = 1;
        int task_status = TASK_STATUS_DONE;
        for (int i = 0; i < list.size(); i++) {
            //开启事务
            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
            // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 设置嵌套事务
            TransactionStatus status = transactionManager.getTransaction(dt);

            SmsTeacherInfo smsTeacherInfo = list.get(i);
            try {
                List<Integer> orgIdList = new ArrayList<>();

                //必填字段验证
                if (isNullOrEmpty(smsTeacherInfo.getTchNo()) || isNullOrEmpty(smsTeacherInfo.getTchName()) || isNullOrEmpty(smsTeacherInfo.getTchTel())
                        || isNullOrEmpty(smsTeacherInfo.getTchOrg())) {
                    transactionManager.rollback(status);
                    createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_INVALID_PARAM, (i + OFFSET_ROW) + "");
                    task_status = TASK_STATUS_ERR;
                    continue;
                }

                //去除名字空格
                String newName = smsTeacherInfo.getTchName().replace(" ", "");
                smsTeacherInfo.setTchName(newName);

//                //验证辅导员 填写四项信息是否正确
//                if (smsTeacherInfo.getIsAssistant().equals("是")) {
//                    if (isNullOrEmpty(smsTeacherInfo.getTchCollege()) || isNullOrEmpty(smsTeacherInfo.getTchMajor())
//                            || isNullOrEmpty(smsTeacherInfo.getTchGrade()) || isNullOrEmpty(smsTeacherInfo.getTchClass())) {
//                        transactionManager.rollback(status);
//                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_INVALID_ASSISTANT, (i + OFFSET_ROW) + "");
//                        task_status = TASK_STATUS_ERR;
//                        continue;
//                    }
//                    QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
//                    List<SmsOrgStructure> orgList = smsOrgStructureMapper.selectList(orgWrapper);
//                    orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, smsTeacherInfo.getTchCollege());
//                    SmsOrgStructure collegeOrg = smsOrgStructureMapper.selectOne(orgWrapper);
//                    if (collegeOrg == null) {
//                        transactionManager.rollback(status);
//                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_ORG_COLLEGE_NOT_EXIST, (i + OFFSET_ROW) + "");
//                        task_status = TASK_STATUS_ERR;
//                        continue;
//                    }
//                    List<Node> nodeList = new ArrayList<>();
//                    for (SmsOrgStructure structure : orgList) {
//                        Node node = new Node();
//                        BeanUtils.copyProperties(structure, node);
//                        nodeList.add(node);
//                    }
//                    Node collegeNode = nodeTreeUtil.getChildNodesTree(nodeList, collegeOrg.getId());
//                    List<Node> childNode = collegeNode.getChildNodeList();
//                    List<Node> majorNode = childNode.stream()
//                            .filter(node -> node.getOrgName().equals(smsTeacherInfo.getTchMajor()))
//                            .collect(Collectors.toList());
//                    if (majorNode.size() < 1) {
//                        transactionManager.rollback(status);
//                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_ORG_MAJOR_NOT_EXIST, (i + OFFSET_ROW) + "");
//                        task_status = TASK_STATUS_ERR;
//                        continue;
//                    }
//                    List<Node> gradeNode = majorNode.get(0).getChildNodeList().stream()
//                            .filter(node -> node.getOrgName().equals(smsTeacherInfo.getTchGrade()))
//                            .collect(Collectors.toList());
//                    if (gradeNode.size() < 1) {
//                        transactionManager.rollback(status);
//                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_ORG_GRADE_NOT_EXIST, (i + OFFSET_ROW) + "");
//                        task_status = TASK_STATUS_ERR;
//                        continue;
//                    }
//                    List<Node> classNode = gradeNode.get(0).getChildNodeList().stream()
//                            .filter(node -> node.getOrgName().equals(smsTeacherInfo.getTchClass()))
//                            .collect(Collectors.toList());
//                    if (classNode.size() < 1) {
//                        transactionManager.rollback(status);
//                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_ORG_CLASS_NOT_EXIST, (i + OFFSET_ROW) + "");
//                        task_status = TASK_STATUS_ERR;
//                        continue;
//                    }
//                    //添加班级组织
//                    orgIdList.add(classNode.get(0).getId());
//                }
                //组织字段验证
                boolean is_continue = false;
                String org = smsTeacherInfo.getTchOrg();
                String[] org_arr = org.split("\\|");
                for (int j = 0; j < org_arr.length; j++) {
                    QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
                    orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, org_arr[j]);
                    SmsOrgStructure orgStructure = smsOrgStructureMapper.selectOne(orgWrapper);
                    if (orgStructure == null) {
                        is_continue = true;
                        break;
                    }
                    orgIdList.add(orgStructure.getId());
                }
                if (is_continue) {
                    transactionManager.rollback(status);
                    createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_ORG_NOT_EXIST, (i + OFFSET_ROW) + "");
                    task_status = TASK_STATUS_ERR;
                    continue;
                }

                String teacher_id;
                String user_id;

                //工号验证 更新 添加
                if (type.equals(UPDATE_TYPE_UPDATE_ADD)) {
                    QueryWrapper<SmsTeacherInfo> teacherWrapper = new QueryWrapper<>();
                    teacherWrapper.lambda().eq(SmsTeacherInfo::getTchNo, smsTeacherInfo.getTchNo());
                    List<SmsTeacherInfo> teacherInfoList = smsTeacherInfoMapper.selectList(teacherWrapper);
                    if (teacherInfoList != null && teacherInfoList.size() > 0) {
                        smsTeacherInfoMapper.update(smsTeacherInfo, teacherWrapper);

                        QueryWrapper<SmsUser> userWrapper = new QueryWrapper<>();
                        userWrapper.lambda().eq(SmsUser::getUsername, smsTeacherInfo.getTchNo());
                        SmsUser smsUser = smsUserMapper.selectOne(userWrapper);
                        //TODO 是否需要更新用户信息
                        if (smsUser != null) {
                            smsUser.setRealName(smsTeacherInfo.getTchName());
                            smsUser.setTel(smsTeacherInfo.getTchTel());
                            smsUserMapper.updateById(smsUser);
                        }else{
                            //用户信息添加
                            SmsUser user = new SmsUser();
                            user.setFlag(TEACHER_FLAG);
                            user.setPassword(DEFAULT_PASSWORD);
                            user.setUsername(smsTeacherInfo.getTchNo());
                            user.setTel(smsTeacherInfo.getTchTel());
                            user.setRealName(smsTeacherInfo.getTchName());
                            smsUserMapper.insert(user);
                            user_id = user.getId();

                            addTeacherUserRelation(user_id, teacherInfoList.get(0).getId(), orgIdList, smsTeacherInfo);
                        }
                    } else {
                        smsTeacherInfoMapper.insert(smsTeacherInfo);
                        if (isNullOrEmpty(smsTeacherInfo.getId())) {
                            // 手动回滚事务
                            transactionManager.rollback(status);
                            createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_FAIL, (i + OFFSET_ROW) + "");
                            task_status = TASK_STATUS_ERR;
                            continue;
                        }
                        teacher_id = smsTeacherInfo.getId();

                        //用户信息添加
                        QueryWrapper<SmsUser> userWrapper = new QueryWrapper<>();
                        userWrapper.lambda().eq(SmsUser::getUsername, smsTeacherInfo.getTchNo());
                        smsUserMapper.delete(userWrapper);

                        SmsUser user = new SmsUser();
                        user.setFlag(TEACHER_FLAG);
                        user.setPassword(DEFAULT_PASSWORD);
                        user.setUsername(smsTeacherInfo.getTchNo());
                        user.setTel(smsTeacherInfo.getTchTel());
                        user.setRealName(smsTeacherInfo.getTchName());
                        smsUserMapper.insert(user);
                        user_id = user.getId();

                        addTeacherUserRelation(user_id, teacher_id, orgIdList, smsTeacherInfo);
                    }
                } else {
                    smsTeacherInfoMapper.delete(new QueryWrapper<SmsTeacherInfo>()
                            .lambda()
                            .eq(SmsTeacherInfo::getTchNo, smsTeacherInfo.getTchNo()));
                    smsTeacherInfoMapper.insert(smsTeacherInfo);
                    if (isNullOrEmpty(smsTeacherInfo.getId())) {
                        // 手动回滚事务
                        transactionManager.rollback(status);
                        createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_FAIL, (i + OFFSET_ROW) + "");
                        task_status = TASK_STATUS_ERR;
                        continue;
                    }
                    teacher_id = smsTeacherInfo.getId();

                    //用户信息添加
                    QueryWrapper<SmsUser> userWrapper = new QueryWrapper<>();
                    userWrapper.lambda().eq(SmsUser::getUsername, smsTeacherInfo.getTchNo());
                    smsUserMapper.delete(userWrapper);

                    SmsUser user = new SmsUser();
                    user.setFlag(TEACHER_FLAG);
                    user.setPassword(DEFAULT_PASSWORD);
                    user.setUsername(smsTeacherInfo.getTchNo());
                    user.setTel(smsTeacherInfo.getTchTel());
                    user.setRealName(smsTeacherInfo.getTchName());
                    smsUserMapper.insert(user);
                    user_id = user.getId();

                    addTeacherUserRelation(user_id, teacher_id, orgIdList, smsTeacherInfo);
                }
                // 手动提交事务
                transactionManager.commit(status);
            } catch (Exception e) {
                e.printStackTrace();
                // 手动回滚事务
                transactionManager.rollback(status);
                createTeacherImportTaskDetail(smsTeacherInfo.getTchNo(), smsTeacherInfo.getTchName(), task_id, REASON_FAIL, (i + OFFSET_ROW) + "");
            } finally {
                if (status.isNewTransaction() && !status.isCompleted()) {
                    transactionManager.commit(status);
                }
            }
        }
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setId(task_id);
        smsImportTask.setStatus(task_status);
        smsImportTaskMapper.updateById(smsImportTask);
    }

    private void addTeacherUserRelation(String user_id, String teacher_id, List<Integer> orgIdList, SmsTeacherInfo smsTeacherInfo) {
        //教师与用户关系表
        //清除原有关系
        QueryWrapper<SmsUserTeacherRelation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.lambda().eq(SmsUserTeacherRelation::getTchId, teacher_id)
                .or().eq(SmsUserTeacherRelation::getUserId, user_id);
        smsUserTeacherRelationMapper.delete(relationQueryWrapper);

        SmsUserTeacherRelation smsUserTeacherRelation = new SmsUserTeacherRelation();
        smsUserTeacherRelation.setUserId(user_id);
        smsUserTeacherRelation.setTchId(teacher_id);
        smsUserTeacherRelationMapper.insert(smsUserTeacherRelation);

        //用户与组织架构关系表
        //清除已存在关系
        QueryWrapper<SmsOrgUserRelation> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(SmsOrgUserRelation::getUserId, user_id);
        smsOrgUserRelationMapper.delete(deleteWrapper);

        for (Integer org_id : orgIdList) {
            SmsOrgUserRelation orgUserRelation = new SmsOrgUserRelation();
            orgUserRelation.setOrgId(org_id.toString());
            orgUserRelation.setUserId(user_id);
            smsOrgUserRelationMapper.insert(orgUserRelation);
        }

        //用户与角色关系表
        //清除已存在关系
        QueryWrapper<SmsUserRoleRelation> roleWrapper = new QueryWrapper<>();
        roleWrapper.lambda().eq(SmsUserRoleRelation::getUserId, user_id);
        smsUserRoleRelationMapper.delete(roleWrapper);

        SmsUserRoleRelation roleRelation = new SmsUserRoleRelation();
        roleRelation.setRoleId(ROLE_TEACHER + "");
        roleRelation.setUserId(user_id);
        smsUserRoleRelationMapper.insert(roleRelation);
        //添加辅导员角色
//        if (smsTeacherInfo.getIsAssistant().equals("是")) {
//            SmsRole smsRole = smsRoleMapper.selectOne(new QueryWrapper<SmsRole>()
//                    .lambda()
//                    .eq(SmsRole::getRoleName, "辅导员"));
//            if (smsRole != null && smsRole.getId() != null) {
//                SmsUserRoleRelation assistantRoleRelation = new SmsUserRoleRelation();
//                assistantRoleRelation.setRoleId(smsRole.getId());
//                assistantRoleRelation.setUserId(user_id);
//                smsUserRoleRelationMapper.insert(assistantRoleRelation);
//            }
//        }
    }

    private void updateTeacherUserRelation(String user_id, String teacher_id, List<Integer> orgIdList, SmsTeacherInfo smsTeacherInfo) {
        //用户与组织架构关系表
        for (Integer org_id : orgIdList) {
            SmsOrgUserRelation smsOrgUserRelation = smsOrgUserRelationMapper.selectOne(new LambdaQueryWrapper<SmsOrgUserRelation>()
                    .eq(SmsOrgUserRelation::getOrgId, org_id)
                    .eq(SmsOrgUserRelation::getUserId, user_id));
            if (!isNullOrEmpty(smsOrgUserRelation) && !isNullOrEmpty(smsOrgUserRelation.getId())) {
                continue;
            }

            SmsOrgUserRelation orgUserRelation = new SmsOrgUserRelation();
            orgUserRelation.setOrgId(org_id.toString());
            orgUserRelation.setUserId(user_id);
            smsOrgUserRelationMapper.insert(orgUserRelation);
        }

        //用户与角色关系表
        //添加辅导员角色
        SmsRole smsRole = smsRoleMapper.selectOne(new QueryWrapper<SmsRole>()
                .lambda()
                .eq(SmsRole::getRoleName, "辅导员"));
        if (smsRole != null && smsRole.getId() != null) {
            SmsUserRoleRelation userRoleRelation = smsUserRoleRelationMapper.selectOne(new LambdaQueryWrapper<SmsUserRoleRelation>()
                    .eq(SmsUserRoleRelation::getUserId, user_id)
                    .eq(SmsUserRoleRelation::getRoleId, smsRole.getId()));
            boolean bl = false;
            if (userRoleRelation != null && !isNullOrEmpty(userRoleRelation.getId())) {
                bl = true;
            }
            if (smsTeacherInfo.getIsAssistant().equals("否") && bl) {
                smsUserRoleRelationMapper.deleteById(userRoleRelation.getId());
            } else if (smsTeacherInfo.getIsAssistant().equals("是") && !bl) {
                SmsUserRoleRelation assistantRoleRelation = new SmsUserRoleRelation();
                assistantRoleRelation.setRoleId(smsRole.getId());
                assistantRoleRelation.setUserId(user_id);
                smsUserRoleRelationMapper.insert(assistantRoleRelation);
            }
        }
    }

    private void createTeacherImportTaskDetail(String no, String name, String task_id, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(task_id);
        smsImportTaskDetail.setFailReason(reason);
        smsImportTaskDetail.setFailName(name);
        smsImportTaskDetail.setFailNo(no);
        smsImportTaskDetail.setFailRow(row);
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }

    @Override
    public ResponseResult getOrgTree(String level) {
        List<SmsOrgStructure> orgStructures = list();
        List<SmsOrgStructureResp> orgStructureRespList = new ArrayList<>();
        if (orgStructures != null && orgStructures.size() > 0) {
            for (SmsOrgStructure smsOrgStructure : orgStructures) {
                SmsOrgStructureResp resp = new SmsOrgStructureResp();
                BeanUtils.copyProperties(smsOrgStructure, resp);
                orgStructureRespList.add(resp);
            }
        }
        List<OrgNode> orgNodes = orgStructureRespList.stream()
                .filter(org -> org.getParentId()
                        .equals(0))
                .map(org -> covertOrgNode(org, orgStructureRespList))
                .filter(orgNode -> {
                    if (!isNullOrEmpty(level)) {
                        return orgNode.getLevel().equals(level);
                    }
                    return true;
                })
                .collect(Collectors.toList());

        return CommonResult.success(orgNodes);
    }

    @Override
    public ResponseResult getOrgCollageTree() {
        List<SmsOrgStructure> orgStructures = list();
        List<SmsOrgStructureResp> orgStructureRespList = new ArrayList<>();
        if (orgStructures != null && orgStructures.size() > 0) {
            for (SmsOrgStructure smsOrgStructure : orgStructures) {
                SmsOrgStructureResp resp = new SmsOrgStructureResp();
                BeanUtils.copyProperties(smsOrgStructure, resp);
                orgStructureRespList.add(resp);
            }
        }
        List<OrgNode> orgNodes = orgStructureRespList.stream()
                .filter(org -> org.getLevel()
                        .equals(String.valueOf(ORG_TYPE_COLLEGE)))
                .map(org -> covertOrgNode(org, orgStructureRespList))
                .collect(Collectors.toList());
        return CommonResult.success(orgNodes);
    }

    @Override
    public ResponseResult getOrgByID(Integer id) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsOrgStructure smsOrgStructure = getById(id);
        if (smsOrgStructure == null) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        SmsOrgStructureResp smsOrgStructureResp = new SmsOrgStructureResp();
        BeanUtils.copyProperties(smsOrgStructure, smsOrgStructureResp);
        return CommonResult.success(smsOrgStructureResp);
    }

    @Override
    public ResponseResult getRootOrgList() {
        List<SmsOrgStructureResp> list = smsOrgStructureMapper.selectList(new QueryWrapper<SmsOrgStructure>()
                        .lambda()
                        .eq(SmsOrgStructure::getLevel, ORG_TYPE_ROOT))
                .stream()
                .map(org -> {
                    SmsOrgStructureResp smsOrgStructureResp = new SmsOrgStructureResp();
                    BeanUtils.copyProperties(org, smsOrgStructureResp);
                    return smsOrgStructureResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(list);
    }

    @Override
    public ResponseResult addOrg(SmsOrgStructureAddReq smsOrgStructureAddReq) {
        if (isNullOrEmpty(smsOrgStructureAddReq.getParentId()) || isNullOrEmpty(smsOrgStructureAddReq.getOrgName())
                || isNullOrEmpty(smsOrgStructureAddReq.getLevel())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (smsOrgStructureAddReq.getParentId() != 0) {
            SmsOrgStructure sos = getById(smsOrgStructureAddReq.getParentId());
            if (sos == null) {
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }
        }
        if (smsOrgStructureAddReq.getLevel().equals(ORG_TYPE_GRADE + "")) {
            if (smsOrgStructureAddReq.getOrgName().length() != 5) {
                return CommonResult.failed(CommonCodeEnum.ORG_GRADE_ERR);
            }
        }

        // 使用split方法按"|"分割字符串
        String[] numberArray = smsOrgStructureAddReq.getOrgName().split("\\|");

        // 直接将结果数组放入集合
        List<String> numbersSet = Arrays.asList(numberArray);

        List<SmsOrgStructure> list = numbersSet.stream().distinct()
                .filter(orgName -> !isNullOrEmpty(orgName))
                .map(orgName -> {
                    SmsOrgStructure smsOrgStructure = new SmsOrgStructure();
                    BeanUtils.copyProperties(smsOrgStructureAddReq, smsOrgStructure);
                    smsOrgStructure.setOrgName(orgName);
                    smsOrgStructure.setOrgInfo(orgName);
                    return smsOrgStructure;
                })
                .collect(Collectors.toList());
        saveBatch(list);
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateOrg(SmsOrgStructureUpdateReq smsOrgStructureUpdateReq) {
        if (isNullOrEmpty(smsOrgStructureUpdateReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsOrgStructure sos = getById(smsOrgStructureUpdateReq.getId());
        if (sos == null) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        SmsOrgStructure smsOrgStructure = new SmsOrgStructure();
        BeanUtils.copyProperties(smsOrgStructureUpdateReq, smsOrgStructure);
        smsOrgStructure.setUpdateTime(new Date());
        boolean bl = updateById(smsOrgStructure);
        if (!bl) {
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteOrg(Integer org_id) {
        if (isNullOrEmpty(org_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsOrgStructure sos = getById(org_id);
        if (sos == null) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        if (sos.getCanDeleted() == 0) {
            return CommonResult.failed(CommonCodeEnum.ORG_CAN_NOT_DELETE);
        }
        boolean bl = removeById(org_id);
        if (!bl) {
            return CommonResult.failed(CommonCodeEnum.DELETE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getOrgUserInfo(Integer org_id, Integer flag, String search_str, Integer pageSize, Integer pageNum) {
        if (isNullOrEmpty(flag)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsUser> userList;
        Integer total;
        if (isNullOrEmpty(org_id)) {
            QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
            if (!isNullOrEmpty(search_str)) {
                queryWrapper.lambda().like(SmsUser::getRealName, search_str);
            }
            Page<SmsUser> page = new Page<>(pageNum, pageSize);
            smsUserMapper.selectPage(page, queryWrapper);
            userList = page.getRecords();
            total = (int) page.getTotal();
        } else {
            SmsOrgStructure orgStructure = smsOrgStructureMapper.selectById(org_id);
            if (orgStructure == null) {
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }

            QueryWrapper<SmsOrgStructure> queryWrapper = new QueryWrapper<>();
            List<SmsOrgStructure> list = smsOrgStructureMapper.selectList(queryWrapper);
            List<OrgNode> orgNodes = new ArrayList<>();
            for (SmsOrgStructure smsOrgStructure : list) {
                OrgNode orgNode = new OrgNode();
                BeanUtils.copyProperties(smsOrgStructure, orgNode);
                orgNodes.add(orgNode);
            }
            List<Integer> list1 = NodeUtil.getChildNodes(orgNodes, org_id);

            userList = smsOrgStructureMapper.getUserListByOrgList(list1, flag, search_str, pageSize, (pageNum - 1) * pageSize);
            total = smsOrgStructureMapper.getUserListByOrgListCount(list1, flag, search_str);
        }

        List<OrgUserInfoResp> orgUserInfoRespList = new ArrayList<>();
        if (userList != null && userList.size() > 0) {
            for (SmsUser smsUser : userList) {
                OrgUserInfoResp orgUserInfoResp = new OrgUserInfoResp();
                BeanUtils.copyProperties(smsUser, orgUserInfoResp);
                List<String> roleNameList = smsOrgStructureMapper.getRoleNameByUser(smsUser.getId());
                List<String> orgNameList = smsOrgStructureMapper.getOrgNameByUser(smsUser.getId());
                orgUserInfoResp.setRoleNameList(roleNameList);
                orgUserInfoResp.setOrgNameList(orgNameList);
                orgUserInfoRespList.add(orgUserInfoResp);
            }
        }
        return CommonResult.success(orgUserInfoRespList, total);
    }

    @Override
    public ResponseResult getOrgUserDetail(String user_id) {
        if (isNullOrEmpty(user_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsUser smsUser = smsUserMapper.selectById(user_id);
        if (smsUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        OrgUserDetailResp orgUserDetailResp = new OrgUserDetailResp();
        BeanUtils.copyProperties(smsUser, orgUserDetailResp);

        QueryWrapper<SmsUserRoleRelation> userRoleRelationQueryWrapper = new QueryWrapper<>();
        userRoleRelationQueryWrapper.lambda().eq(SmsUserRoleRelation::getUserId, user_id);
        List<SmsUserRoleRelation> userRoleRelations = smsUserRoleRelationMapper.selectList(userRoleRelationQueryWrapper);
        List<String> roleList = new ArrayList<>();
        if (userRoleRelations != null && userRoleRelations.size() > 0) {
            for (SmsUserRoleRelation userRoleRelation : userRoleRelations) {
                String role_id = userRoleRelation.getRoleId();
                SmsRole smsRole = smsRoleMapper.selectById(role_id);
                if (smsRole != null) {
                    roleList.add(role_id);
                }
            }
        }
        orgUserDetailResp.setRoleList(roleList);

        QueryWrapper<SmsOrgUserRelation> orgUserRelationQueryWrapper = new QueryWrapper<>();
        orgUserRelationQueryWrapper.lambda().eq(SmsOrgUserRelation::getUserId, user_id);
        List<SmsOrgUserRelation> orgUserRelations = smsOrgUserRelationMapper.selectList(orgUserRelationQueryWrapper);
        List<String> orgStructureList = new ArrayList<>();
        if (orgUserRelations != null && orgUserRelations.size() > 0) {
            for (SmsOrgUserRelation smsOrgUserRelation : orgUserRelations) {
                String org_id = smsOrgUserRelation.getOrgId();
                SmsOrgStructure smsOrgStructure = smsOrgStructureMapper.selectById(org_id);
                if (smsOrgStructure != null) {
                    orgStructureList.add(org_id);
                }
            }
        }
        orgUserDetailResp.setOrgList(orgStructureList);
        return CommonResult.success(orgUserDetailResp);
    }

    @Override
    @Transactional
    public ResponseResult updateUserDetail(OrgUserDetailReq orgUserDetailReq, String user_id) {
        if (isNullOrEmpty(orgUserDetailReq.getId(), orgUserDetailReq.getRealName(), orgUserDetailReq.getTel())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //更新用户信息
        SmsUser originUser = smsUserMapper.selectById(orgUserDetailReq.getId());
        if (originUser == null) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        SmsUser smsUser = new SmsUser();
        if (!orgUserDetailReq.getRealName().equals("")) {
            smsUser.setRealName(orgUserDetailReq.getRealName());
        }
        if (!orgUserDetailReq.getTel().equals(originUser.getTel()) && !orgUserDetailReq.getTel().equals("")) {
            QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsUser::getTel, orgUserDetailReq.getTel());
            List<SmsUser> telList = smsUserMapper.selectList(queryWrapper);
            if (telList != null && telList.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.TEL_EXIST);
            }
            smsUser.setTel(orgUserDetailReq.getTel());
        }
        smsUser.setId(orgUserDetailReq.getId());
        smsUserMapper.updateById(smsUser);

        //修改用户对应个人信息
        if (originUser.getFlag() == TEACHER_FLAG && !orgUserDetailReq.getTel().equals(originUser.getTel())) {
            SmsUserTeacherRelation userTeacherRelation = smsUserTeacherRelationMapper.selectOne(new LambdaQueryWrapper<SmsUserTeacherRelation>()
                    .eq(SmsUserTeacherRelation::getUserId, originUser.getId()));
            SmsTeacherInfo teacherInfo = smsTeacherInfoMapper.selectById(userTeacherRelation.getTchId());
            if (isNullOrEmpty(teacherInfo)) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.TEACHER_NOT_EXIST));
            }
            List<SmsTeacherInfo> teacherInfoList = smsTeacherInfoMapper.selectList(new LambdaQueryWrapper<SmsTeacherInfo>()
                    .eq(SmsTeacherInfo::getTchTel, originUser.getTel())
                    .ne(SmsTeacherInfo::getId, teacherInfo.getId()));
            if (teacherInfoList != null && teacherInfoList.size() > 0) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.TEACHER_TEL_EXIST));
            }
            teacherInfo.setTchTel(originUser.getTel());
            teacherInfo.setTchName(originUser.getRealName());
            smsTeacherInfoMapper.updateById(teacherInfo);
        }

        //更新用户角色关系
        List<String> roleList = orgUserDetailReq.getRoleList();
        if (roleList != null && roleList.size() > 0) {
            QueryWrapper<SmsUserRoleRelation> roleWrapper = new QueryWrapper<>();
            roleWrapper.lambda().eq(SmsUserRoleRelation::getUserId, orgUserDetailReq.getId());
            smsUserRoleRelationMapper.delete(roleWrapper);
            for (String role_id : roleList) {
                SmsRole smsRole = smsRoleMapper.selectById(role_id);
                if (smsRole == null) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ROLE_NOT_EXIST));
                }
                SmsUserRoleRelation roleRelation = new SmsUserRoleRelation();
                roleRelation.setRoleId(role_id);
                roleRelation.setUserId(orgUserDetailReq.getId());
                smsUserRoleRelationMapper.insert(roleRelation);
            }
        }

        //更新用户组织关系
        List<String> orgList = orgUserDetailReq.getOrgList();
        if (orgList != null && orgList.size() > 0) {
            QueryWrapper<SmsOrgUserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsOrgUserRelation::getUserId, orgUserDetailReq.getId());
            smsOrgUserRelationMapper.delete(queryWrapper);
            for (String org_id : orgList) {
                SmsOrgStructure smsOrgStructure = smsOrgStructureMapper.selectById(org_id);
                if (smsOrgStructure == null) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST));
                }
                SmsOrgUserRelation orgUserRelation = new SmsOrgUserRelation();
                orgUserRelation.setOrgId(org_id);
                orgUserRelation.setUserId(orgUserDetailReq.getId());
                smsOrgUserRelationMapper.insert(orgUserRelation);
            }
        }

        //更新缓存
        cacheUtil.saveRoleListAndUserInfo(user_id);
        cacheUtil.saveOrgListAndUserInfo(user_id);

        return CommonResult.success();
    }

    private OrgNode covertOrgNode(SmsOrgStructureResp menu, List<SmsOrgStructureResp> menuList) {
        OrgNode node = new OrgNode();
        BeanUtils.copyProperties(menu, node);
        List<OrgNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId()
                        .equals(menu.getId()))
                .map(subMenu -> covertOrgNode(subMenu, menuList))
                .collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    @Override
    public ResponseResult getAppointUser(Integer processObjectType, String processObjectId) {
        if (processObjectType == ORG_OBJECT_TYPE_ROLE) {
            List<SmsSearchUserResp> smsSearchUserResps = smsUserRoleRelationMapper.selectList(new QueryWrapper<SmsUserRoleRelation>()
                            .lambda()
                            .eq(SmsUserRoleRelation::getRoleId, processObjectId))
                    .stream()
                    .map(smsUser -> {
                        SmsSearchUserResp smsSearchUserResp = new SmsSearchUserResp();
                        SmsUser userInfo = cacheUtil.getUserInfo(smsUser.getUserId());
                        if (userInfo != null) {
                            BeanUtils.copyProperties(userInfo, smsSearchUserResp);

                            List<String> orgNameList = smsOrgStructureMapper.getOrgNameByUser(userInfo.getId());
                            smsSearchUserResp.setOrgNameList(orgNameList);
                        }
                        return smsSearchUserResp;
                    })
                    .collect(Collectors.toList());
            return CommonResult.success(smsSearchUserResps);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult addOrgLeader(SmsOrgStructureLeaderReq addLeaderReq) {
        if (isNullOrEmpty(addLeaderReq.getOrgId(), addLeaderReq.getUserId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验组织
        SmsOrgStructure smsOrgStructure = smsOrgStructureMapper.selectById(addLeaderReq.getOrgId());
        if (isNullOrEmpty(smsOrgStructure)) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        //校验用户
        SmsUser smsUser = smsUserMapper.selectById(addLeaderReq.getUserId());
        if (isNullOrEmpty(smsUser)) {
            return CommonResult.failed(CommonCodeEnum.USER_NOT_EXIST);
        }
        //组织负责人
        smsOrgStructure.setLeader(addLeaderReq.getUserId());
        smsOrgStructureMapper.updateById(smsOrgStructure);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getOrgLeader(Integer orgId) {
        if (isNullOrEmpty(orgId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsOrgStructureLeaderResp smsOrgStructureLeaderResp = new SmsOrgStructureLeaderResp();
        //校验组织
        SmsOrgStructure smsOrgStructure = smsOrgStructureMapper.selectById(orgId);
        if (isNullOrEmpty(smsOrgStructure)) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        smsOrgStructureLeaderResp.setOrgId(orgId);
        //组织负责人id
        String leaderId = smsOrgStructure.getLeader();
        if (isNullOrEmpty(leaderId)) {
            smsOrgStructureLeaderResp.setIsLeader(false);
        } else {
            smsOrgStructureLeaderResp.setIsLeader(true);
            SmsUser smsUser = smsUserMapper.selectById(leaderId);
            if (!isNullOrEmpty(smsUser)) {
                OrgUserInfoResp orgUserInfoResp = new OrgUserInfoResp();
                BeanUtils.copyProperties(smsUser, orgUserInfoResp);
                smsOrgStructureLeaderResp.setLeaderUserInfo(orgUserInfoResp);
            }
        }
        return CommonResult.success(smsOrgStructureLeaderResp);
    }

    @Override
    public ResponseResult deletedOrgLeader(SmsOrgStructureLeaderReq deletedLeaderReq) {
        if (isNullOrEmpty(deletedLeaderReq.getOrgId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验组织
        SmsOrgStructure smsOrgStructure = smsOrgStructureMapper.selectById(deletedLeaderReq.getOrgId());
        if (isNullOrEmpty(smsOrgStructure)) {
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        //删除负责人
        smsOrgStructure.setLeader("");
        smsOrgStructureMapper.updateById(smsOrgStructure);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getUserDepartmentList(String user_id) {
        if (isNullOrEmpty(user_id)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<Integer> orgList = cacheUtil.getOrgList(user_id).stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<SmsOrgStructureResp> userDepartmentIdList = commonUtil.getUserDepartmentIdList(orgList)
                .stream()
                .map(orgId ->{
                    SmsOrgStructureResp smsOrgStructureResp = new SmsOrgStructureResp();
                    SmsOrgStructure organisation = smsOrgStructureMapper.selectById(orgId);
                    BeanUtils.copyProperties(organisation, smsOrgStructureResp);
                    return smsOrgStructureResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(userDepartmentIdList);
    }

    @Override
    public ResponseResult getOneLevelOrgList() {
        List<SmsOrgStructureResp> list = smsOrgStructureMapper.selectList(new LambdaQueryWrapper<SmsOrgStructure>()
                .eq(SmsOrgStructure::getLevel,"1"))
                .stream()
                .map(org -> {
                    SmsOrgStructureResp smsOrgStructureResp = new SmsOrgStructureResp();
                    BeanUtils.copyProperties(org, smsOrgStructureResp);
                    return smsOrgStructureResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(list);
    }


}
